package com.movecar.utils;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;

import com.movecar.R;
import com.movecar.dialog.CustomDialog;
import com.movecar.utils.ConfigCacheUtil.ConfigCacheModel;
import com.movecar.utils.ProgressOutHttpEntity.ProgressListener;
import com.movecar.widget.MyProgress;

public class HttpPostRequestAsyncTask extends AsyncTask<List<NameValuePair>, Integer, String> {
	public int serviceMsgWhat;
	public RequestResultCallback requestCallback = null;
	public Class<?> modelClass;
	public String mUrl;
	private Context context;
	private MyProgress mProgress;
	private long totalSize;

	public HttpPostRequestAsyncTask(RequestResultCallback requestCallback, Class<?> modelClass, String mUrl) {
		super();
		this.requestCallback = requestCallback;
		this.modelClass = modelClass;
		this.mUrl = mUrl;
	}

	public HttpPostRequestAsyncTask(Context context, RequestResultCallback requestCallback, Class<?> modelClass,
			String mUrl) {
		super();
		this.requestCallback = requestCallback;
		this.modelClass = modelClass;
		this.mUrl = mUrl;
		this.context = context;

	}

	@Override
	protected void onPreExecute() {// 执行前的初始化
		if (null != context) {

			final LayoutInflater inflater = LayoutInflater.from(context);
			View v = inflater.inflate(R.layout.progress, null);
			mProgress = (MyProgress) v.findViewById(R.id.progress);
			CustomDialog.Builder customBuilder = new CustomDialog.Builder(context);
			ImageView img = new ImageView(context);
			img.setImageResource(R.drawable.ic_launcher);
			customBuilder.setImgIcon(img).setTitle("上传中。。。").setContentView(v);

			customBuilder.create().show();

		}
		super.onPreExecute();
	}

	@Override
	protected String doInBackground(List<NameValuePair>... params) {

		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < params[0].size(); i++) {

			sb.append(params[0].get(i).getValue());
		}

		String cID = FileUtils.stringToMD5(mUrl + sb);
		if (ConfigCacheUtil.getUrlCache(cID, ConfigCacheModel.CONFIG_CACHE_MODEL_MEDIUM) != null) {
			return ConfigCacheUtil.getUrlCache(cID, ConfigCacheModel.CONFIG_CACHE_MODEL_MEDIUM);
		} else {
			if (params[0].get(0).getValue().equals("saveShareNew1")) {

				MultipartEntityBuilder entity = MultipartEntityBuilder.create();
				entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
				ContentType TEXT_PLAIN = ContentType.create("text/plain", Charset.forName(HTTP.UTF_8));
				for (int index = 0; index < params[0].size(); index++) {
					if (params[0].get(index).getName().contains("picFile")) {
						// If the key equals to "image", we use FileBody to
						// transfer
						// the data
						if (null != params[0].get(index).getValue()) {
							entity.addPart(params[0].get(index).getName(), new FileBody(new File(params[0].get(index)
									.getValue())));
						}

					} else {
						// Normal string data
						StringBody temp = new StringBody(params[0].get(index).getValue(), TEXT_PLAIN);
						entity.addPart(params[0].get(index).getName(), temp);
					}
				}
				HttpEntity postEntity = entity.build();// 生成 HTTP POST 实体
				totalSize = postEntity.getContentLength();// 获取上传文件的大小

				ProgressOutHttpEntity progressHttpEntity = new ProgressOutHttpEntity(postEntity,
						new ProgressListener() {
							@Override
							public void transferred(long transferedBytes) {
								publishProgress((int) (100 * transferedBytes / totalSize));// 更新进度
							}
						});

				return post(params[0], progressHttpEntity);
			} else {
				return requestServer(params[0]);
			}

		}

	}

	public String requestServer(List<NameValuePair> params) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < params.size(); i++) {

			sb.append(params.get(i).getValue());
		}
		String cID = FileUtils.stringToMD5(mUrl + sb);
		String responseStr = null;
		HttpClient httpClient = new DefaultHttpClient(); // 新建HttpClient对象
		HttpPost httpPost = new HttpPost(mUrl); // 新建HttpPost对象
		try {
			HttpEntity entity = new UrlEncodedFormEntity(params, HTTP.UTF_8); // 设置字符集
			Log.e("result", params.toString());

			httpPost.setEntity(entity); // 设置参数实体
			httpPost.addHeader("Accept-Encoding", "gzip");
			HttpResponse httpResp = httpClient.execute(httpPost); // 获取HttpResponse实例

			if (httpResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 响应通过
				String result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
				Log.e("result", result);
				responseStr = result;
				if ("queryOrderNew1".equals(params.get(0).getValue())
						|| "queryAdvertNew1".equals(params.get(0).getValue())) {
					ConfigCacheUtil.setUrlCache(result, cID);
				}
			} else {
				// 响应未通过
				responseStr = null;
			}
		} catch (UnsupportedEncodingException e) {
			responseStr = null;
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			responseStr = null;
			e.printStackTrace();
		} catch (IOException e) {
			responseStr = null;
			e.printStackTrace();
		}

		return responseStr;
	}

	@Override
	protected void onPostExecute(String result) {
		
		if (null != result) {

			requestCallback.onSuccess(result);
		} else {
			requestCallback.onFail("与服务器连接失败");
		}
		super.onPostExecute(result);
	}

	public String post(List<NameValuePair> nameValuePairs, ProgressOutHttpEntity postEntity) {
		String responseStr = null;
		HttpClient httpClient = new DefaultHttpClient();
		HttpContext localContext = new BasicHttpContext();
		HttpPost httpPost = new HttpPost(mUrl);

		try {

			httpPost.setEntity(postEntity);

			HttpResponse response = httpClient.execute(httpPost, localContext);
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // 响应通过
				String result = EntityUtils.toString(response.getEntity(), "UTF-8");
				Log.e("result", result);
				responseStr = result;

			} else {
				responseStr = null;
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return responseStr;
	}

	protected void onProgressUpdate(Integer... progress) {

		int vlaue = progress[0];

		mProgress.setProgress(vlaue);
		super.onProgressUpdate(vlaue);
	}

	public void operator() {
		try {
			// 休眠1秒
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
